package com.zhangwei.day43bluetooth.task;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author zhangwei
 * @version V1.0
 * @Title: Advanced
 * @Package com.zhangwei.day43bluetooth.task
 * @Description:
 * @date 15/10/27 上午10:59
 */

public class ServerThread extends Thread {
    public BluetoothAdapter adapter;
    UUID uuid = UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb");
    private BluetoothDevice device;


    public ServerThread(BluetoothAdapter adapter, BluetoothDevice device) {
        this.adapter = adapter;
        this.device = device;
    }

    @Override
    public void run() {
        super.run();
        FileInputStream fis = null;
        BluetoothServerSocket serverSocket = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {


            serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(device.getName(), uuid);
            BluetoothSocket accept = serverSocket.accept();
            fis = new FileInputStream(new File(""));//文件路径
            byte[] bytes = new byte[2 * 1024];
            int lenth = 0;
            bufferedOutputStream = new BufferedOutputStream(accept.getOutputStream());
            while (-1 != (lenth = fis.read(bytes))) {
                bufferedOutputStream.write(bytes, 0, lenth);
                bufferedOutputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}
